package com.markyao.es.service;

import com.markyao.es.Article_model_es;
import com.markyao.es.EsResult;
import com.markyao.es.repository.ArticleEsRepository;
import com.markyao.vo.EsArticleVo;
import com.markyao.vo.Result;
import com.markyao.vo.parmas.EsParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleEsService {
    @Autowired
    ArticleEsRepository articleEsRepository;

    //TODO: 查找所有
    public EsResult findAllES(int currentPage) {
        return articleEsRepository.findAllEmployeeDetailsFromES(currentPage);
    }

    //TODO: 模糊查询-->通过名title,content,summary字段
    //TODO: 可智能纠错；高亮显示等
    public Result findByFuzziness(EsParams esParams) {
        EsResult esResult = new EsResult();
        if (esParams.getQueryString().equals("")||esParams.getQueryString().length()<=0){
            esResult=findAllES(esParams.getCurrentPage());
            List<Article_model_es> list = esResult.getList();
            Integer totalSize = esResult.getTotalSize();
            int page = totalSize % esParams.getPageSize()==0?
                    totalSize /esParams.getPageSize(): totalSize /esParams.getPageSize()+1;
            return Result.success(copyForList(list),page, totalSize);
        }
        esResult = articleEsRepository.findByFuzziness(esParams);
        List<Article_model_es> data = esResult.getList();
        List<EsArticleVo>esArticleVoList=copyForList(data);
        Integer totalSize = esResult.getTotalSize();
        int page = esResult.getTotalSize() % esParams.getPageSize()==0?
                esResult.getTotalSize()/esParams.getPageSize():esResult.getTotalSize()/esParams.getPageSize()+1;

        return Result.success(esArticleVoList,page,totalSize);

    }

    private List<EsArticleVo> copyForList(List<Article_model_es> data) {
        List<EsArticleVo>esArticleVoList=new ArrayList<>();
        for (Article_model_es datum : data) {
            EsArticleVo esArticleVo=copy(datum);
            esArticleVoList.add(esArticleVo);
        }
        return esArticleVoList;
    }

    private EsArticleVo copy(Article_model_es datum) {
        EsArticleVo esArticleVo=new EsArticleVo();
        BeanUtils.copyProperties(datum,esArticleVo);
        esArticleVo.setId(String.valueOf(datum.getId()));
        return esArticleVo;
    }


    //TODO: completion_suggest智能推荐,通过输入的前缀实现智能推荐(要求时效性)
    public Result findBySuggest(EsParams esParams) {
        List<String> bySuggestList = articleEsRepository.findBySuggest(esParams.getPrefix());
        return parserTextList(bySuggestList);
    }

    //TODO: 统一将得到的推荐String结果转化为result
    private Result parserTextList(List<String> bySuggestList) {
        return Result.success(bySuggestList);
    }

}
